package com.ruoyi.web.controller.wokerSys;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.WebFilenameUtils;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.validator.ValidatorUtils;
import com.ruoyi.worker.constant.Constant;
import com.ruoyi.worker.domain.workAttendance.RzScheduleStaffPlan;
import com.ruoyi.worker.domain.workAttendance.dto.AttendanceShift;
import com.ruoyi.worker.domain.workAttendance.RzScheduleTask;
import com.ruoyi.worker.domain.workAttendance.dto.SchedulePlanDTO;
import com.ruoyi.worker.handler.SchedulingPlanMapImportHandler;
import com.ruoyi.worker.service.TermScheduleService;
import com.ruoyi.worker.service.workerSys.ISchedulingTask;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassTitle: SchedulingApi
 * @ProjectName guiyang-oa
 * @Description: 人资-排班接口
 * @Author Hush. ultraman_zero@aliyun.com
 * @Date 2021/11/16
 * @Time 22:32
 */
@RestController
@RequestMapping("/scheduling")
public class SchedulingApi extends BaseController {

    @Autowired
    private ISchedulingTask iSchedulingTask;

    @Autowired
    private TermScheduleService iAttendance;


    @GetMapping("task/page")
    public TableDataInfo pageScheduling(RzScheduleTask task) {
        startPage();
        List<RzScheduleTask> list = iSchedulingTask.listTask(task);
        return getDataTable(list);
    }

    /**
     * 新建排班任务
     *
     * @param task 排班任务
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/16 22:38
     **/
    @PostMapping("task/new")
    public AjaxResult newScheduling(@RequestBody RzScheduleTask task) {

        ValidatorUtils.validateEntity(task);
        task.setCreator(getUsername())
                .setCreatorId(getUserId())
                .setHandleTime(new Date());
        iSchedulingTask.saveTask(task);
        return AjaxResult.success();
    }

    /**
     * 修改排班
     *
     * @param task 排班任务
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/16 22:38
     **/
    @PostMapping("task/update")
    public AjaxResult updateScheduling(@RequestBody RzScheduleTask task) {

        ValidatorUtils.validateEntity(task);
        task.setUpdater(getUsername())
                .setUpdaterId(getUserId())
                .setHandleTime(new Date());
        iSchedulingTask.updateTask(task);
        return AjaxResult.success();
    }

    /**
     * 删除排班任务
     *
     * @author Hush.
     * @since 2021/11/16 22:38
     **/
    @GetMapping("task/del/{ids}")
    public AjaxResult removeScheduling(@PathVariable Long[] ids) {

        iSchedulingTask.delTaskByIds(ids);
        return AjaxResult.success();
    }

    /**
     * 获取考勤通用班次规则信息 - term_attendance_group 对象
     *
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/17 9:12
     **/
    @GetMapping("attendanceShiftList")
    public AjaxResult getAttendanceShift() {
        List<AttendanceShift> list = iSchedulingTask.listAttendanceShift();
        return AjaxResult.success(list);
    }


    /**
     * 导出排班计划模板
     *
     * @author Hush.
     * @since 2021/11/17 10:15
     **/
    @GetMapping("plan/exportTemplate")
    public void exportSchedulingPlanTemplate(RzScheduleTask task, HttpServletRequest request, ModelMap modelMap, HttpServletResponse response) throws Exception {

        // 一般Excel模板统一放置到某文件夹中，该文件夹路径通过配置参数统一获取
        TemplateExportParams params = new TemplateExportParams("template/RZSchedulingPlan.xlsx");
        params.setColForEach(true);

        SchedulePlanDTO value = iSchedulingTask.generateSchedulingPlanPreviewTemplateData(task);
        Workbook book = ExcelExportUtil.exportExcel(params, value.getValue());
        JSONObject model = value.getModel();
        //若班组人员为空,不创建下拉框 valList::人员列表
        if (model.getIntValue(Constant.ROWS_SIZE)>0){
            ExcelUtil.createDropDownListWithHiddenSheet(book.getSheetAt(0),
                    model.getIntValue(Constant.FIRST_ROW),
                    model.getIntValue(Constant.FIRST_COL),
                    model.getIntValue(Constant.END_ROW),
                    model.getIntValue(Constant.END_COL),
                    (String[]) model.get(Constant.DATA_ARRAY),
                    book, model.getString(Constant.HIDDEN_SHEET_NAME));
        }
        this.out(book, model.getString(Constant.CODED_FILE_NAME), request, response);

    }

    /**
     * 输出excel文件对象
     *
     * @param workbook      excel对象
     * @param codedFileName 文件名称
     * @param request       请求
     * @param response      答复
     * @return void
     * @author Hush.
     * @since 2021/11/18 17:05
     **/
    public void out(Workbook workbook, String codedFileName, HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (workbook instanceof HSSFWorkbook) {
            codedFileName = codedFileName + ".xls";
        } else {
            codedFileName = codedFileName + ".xlsx";
        }

        response.setHeader("content-disposition", WebFilenameUtils.disposition(codedFileName));
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }


    /**
     * 排班计划详情
     *
     * @param searchDto 排班任务检索条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/17 10:15
     **/
    @GetMapping("plan/detail")
    public AjaxResult schedulingPlanDetail(RzScheduleStaffPlan searchDto) throws ParseException {

        return AjaxResult.success(iSchedulingTask.getDetailSchedulingPlan(searchDto));
    }

    /**
     * 导入排班计划模板
     *
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/17 10:15
     **/
    @PostMapping("plan/importTemplate")
    @RepeatSubmit
    public AjaxResult importSchedulingPlanTemplate(MultipartFile file) throws Exception {

        ImportParams params = new ImportParams();
        params.setTitleRows(3);
        params.setDataHandler(new SchedulingPlanMapImportHandler());
        List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);

        RzScheduleTask task = new RzScheduleTask().setCreator(getUsername()).setCreatorId(getUserId()).setHandleTime(new Date());
        iSchedulingTask.dealSchedulingPlanData(list, task);
        //Thread.sleep(10000); //模拟处理excel数据
        return AjaxResult.success();
    }

    /**
     * 覆盖原排班计划
     *
     * @param file:新排班计划文件
     * @param dto:原考勤主任务
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/21 14:47
     */
    @PostMapping("plan/coverSchedulingPlanTemplate")
    @RepeatSubmit
    public AjaxResult coverSchedulingPlanTemplate(MultipartFile file, RzScheduleTask dto) throws Exception {

        ImportParams params = new ImportParams();
        params.setTitleRows(3);
        params.setDataHandler(new SchedulingPlanMapImportHandler());
        List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);

        dto.setUpdater(getUsername()).setUpdaterId(getUserId()).setHandleTime(new Date());
        iSchedulingTask.coverSchedulingPlanData(list, dto);
        return AjaxResult.success();
    }

    /**
     * 校验排班任务模板有无日期冲突
     * @param dto: 检索条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/22 10:59
     */
    @GetMapping("task/shiftDateVerification")
    public AjaxResult shiftDateVerification(RzScheduleTask dto) {

        return AjaxResult.success(iSchedulingTask.checkTaskShiftDate(dto));
    }


    /**
     * 下载排班计划
     *
     * @author Hush.
     * @since 2021/11/17 10:15
     **/
    @GetMapping()
    public void downloadSchedulingPlan(RzScheduleTask task, HttpServletRequest request, ModelMap modelMap, HttpServletResponse response) throws Exception {

    }

}
